package com.markedquilt.homepage.service.impl;

import com.markedquilt.homepage.CourseInfo;
import com.markedquilt.homepage.CourseInfosRequest;
import com.markedquilt.homepage.dao.HomePageCourseDao;
import com.markedquilt.homepage.entity.HomePageCourse;
import com.markedquilt.homepage.service.ICourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ZhangKe
 * @Description 课程服务功能实现
 * @date 2020/12/27 15:25.
 */
@Slf4j
@Service
public class CourseServiceImpl implements ICourseService {

    @Autowired
    private HomePageCourseDao homepageCourseDao;

    @Override
    public CourseInfo getCourseInfo(Long id) {
        Optional<HomePageCourse> course = homepageCourseDao.findById(id);
        return buildCourseInfo(course.orElse(HomePageCourse.invalid()));
    }

    /**
     * 通过ids获取课程信息
     *
     * @param request
     * @return
     */
    @Override
    public List<CourseInfo> getCourseInfos(CourseInfosRequest request) {
        if (CollectionUtils.isEmpty(request.getIds())){
            return Collections.emptyList();
        }
        List<HomePageCourse> courses = homepageCourseDao.findAllById(request.getIds());
        return courses.stream().map(this::buildCourseInfo).collect(Collectors.toList());
    }

    private CourseInfo buildCourseInfo(HomePageCourse course){
        return CourseInfo.builder()
                .id(course.getId())
                .courseName(course.getCourseName())
                .courseType(course.getCourseType()==0 ? "免费课程" : "实战课程")
                .courseIcon(course.getCourseIcon())
                .courseIntro(course.getCourseIntro())
                .build();
    }
}
